package com.kaiwukj.android.ufamily.mvp.ui.page.account.login;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.AuthTask;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.di.component.DaggerAccountComponent;
import com.kaiwukj.android.ufamily.di.module.AccountModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.LoginEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.requestbak.AlipayLoginRequest;
import com.kaiwukj.android.ufamily.mvp.http.entity.requestbak.LoginRequest;
import com.kaiwukj.android.ufamily.mvp.http.entity.requestbak.WechatLoginRequest;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.AuthResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.account.AccountContract;
import com.kaiwukj.android.ufamily.mvp.ui.page.account.AccountPresenter;
import com.kaiwukj.android.ufamily.mvp.ui.widget.SpaceItemDecoration;
import com.kaiwukj.android.ufamily.utils.UserStore;
import com.mob.secverify.CustomUIRegister;
import com.mob.secverify.OperationCallback;
import com.mob.secverify.SecVerify;
import com.mob.secverify.VerifyCallback;
import com.mob.secverify.datatype.UiSettings;
import com.mob.secverify.datatype.VerifyResult;
import com.mob.secverify.exception.VerifyException;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * @author Charles
 * @date 2019/10/10.
 * description：Kaiwu
 */
@Route(path = ARouterUrlKt.LoginRouterUrl)
public class PsdLoginActivity extends BaseMvpActivity<AccountPresenter> implements AccountContract.View {

    @BindView(R.id.container_left)
    ViewGroup containerBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_forget_pass)
    TextView tvForgotPsd;

    @BindView(R.id.tv_login)
    Button tvLogin;
    @BindView(R.id.et_phone_number)
    EditText etPhoneNumber;
    @BindView(R.id.iv_phone_clear)
    ImageView ivPhoneClear;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.tv_eye)
    TextView tvEye;
    @BindView(R.id.tv_login_code)
    TextView tvCodeLogin;
    /*@BindView(R.id.tv_right_nav)
    TextView tvForgotPsd;*/
   /* @BindView(R.id.tv_login_wechat)
    TextView ivWechatLogin;
    @BindView(R.id.tv_login_alipay)
    TextView ivAliLogin;*/

    @BindView(R.id.rv_login_way)
    RecyclerView rvLoginWay;

    @Autowired
    String phone;

    @OnClick({R.id.tv_to_protocol, R.id.tv_to_protocol_private, R.id.tv_login_code, R.id.tv_forget_pass})
    void onClickEvent(View v) {
        switch (v.getId()) {
            case R.id.tv_to_protocol:
                ARouter.getInstance().build(ARouterUrlKt.WebViewUrl)
                        .withString("EXTRA_KEY_WEB_URL", Constant.LOGIN_TIP_WEB_URL)
                        .withString("EXTRA_KEY_WEB_TITLE", "用户协议")
                        .navigation();
                break;
            case R.id.tv_to_protocol_private:
                ARouter.getInstance().build(ARouterUrlKt.WebViewUrl)
                        .withString("EXTRA_KEY_WEB_URL", Constant.H5_PRIVACE)
                        .withString("EXTRA_KEY_WEB_TITLE", "隐私协议")
                        .navigation();
                break;
            case R.id.tv_login_code:
                /*String phone = etPhoneNumber.getText().toString().trim();
                if (RegexUtils.isMobileSimple(phone)) {
                    ARouter.getInstance().build(ARouterUrlKt.CodeLoginRouterUrl)
                            .withString("phone", phone)
                            .navigation();
                } else {
                    ARouter.getInstance().build(ARouterUrlKt.CodeLoginRouterUrl)
                            .navigation();
                }*/

                onBackPressedSupport();

                break;
            case R.id.tv_forget_pass:
                ARouter.getInstance().build(ARouterUrlKt.ForgetPassUrl).navigation();
                break;
        }
    }


    private long backMs;

    private int loginType;
//    1 微信 2 支付宝

    private String mOpenId;

    private String infoStr;

    private String authCode;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerAccountComponent.builder()
                .appComponent(appComponent)
                .accountModule(new AccountModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        return R.layout.activity_psd_login;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        if (!StringUtils.isEmpty(phone)) {
            etPhoneNumber.setText(phone);
        } else {
            etPhoneNumber.setText(UserStore.getUName());
        }

        if (!StringUtils.isEmpty(etPhoneNumber.getText().toString().trim())) {
            ivPhoneClear.setVisibility(View.VISIBLE);
        }

        rvLoginWay.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        rvLoginWay.addItemDecoration(new SpaceItemDecoration(45, RecyclerView.HORIZONTAL));
        List<LoginWayItemEntity> loginWayItemEntities = new ArrayList<>();
        loginWayItemEntities.add(new LoginWayItemEntity(LoginWayItemEntity.WECHAT, R.mipmap.ic_login_way_wechat, "微信"));
        loginWayItemEntities.add(new LoginWayItemEntity(LoginWayItemEntity.ONEKEY, R.mipmap.ic_login_way_fast, "一键登录"));
        LoginWayAdapter loginWayAdapter = new LoginWayAdapter(loginWayItemEntities);
        rvLoginWay.setAdapter(loginWayAdapter);

        loginWayAdapter.setOnItemClickListener((adapter, view, position) -> {
            switch (loginWayAdapter.getLoginWay(position)) {
                case LoginWayItemEntity.WECHAT:
                    loginWechat();
                    break;
                case LoginWayItemEntity.ONEKEY:
                    loginFast();
                    break;
            }
        });

        tvTitle.setVisibility(View.GONE);

        containerBack.setOnClickListener(v -> onBackPressedSupport());

        ivPhoneClear.setOnClickListener(v -> etPhoneNumber.setText(""));
        tvLogin.setOnClickListener(view -> {
            if (TextUtils.isEmpty(etPhoneNumber.getText().toString())) {
                showMessage("请输入手机号码");
                return;
            }
            if (TextUtils.isEmpty(etPassword.getText().toString())) {
                showMessage("请输入密码");
                return;
            }
            LoginRequest loginRequest = new LoginRequest(null, etPhoneNumber.getText().toString(), etPassword.getText().toString());
            // mPresenter.requestLogin(loginRequest);
            mPresenter.loginByPass(etPhoneNumber.getText().toString(), etPassword.getText().toString());
        });
        tvEye.setOnClickListener(view -> {
            tvEye.setSelected(!tvEye.isSelected());
            etPassword.setTransformationMethod(tvEye.isSelected() ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
            etPassword.setSelection(etPassword.getText().length());
        });

    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        //tvRegister.setOnClickListener(view -> ARouter.getInstance().build(ARouterUrlKt.LoginRegisterUrl).navigation());
      /*  tvCodeLogin.setOnClickListener(view -> ARouter.getInstance()
                .build(ARouterUrlKt.AccountEditBySmsUrl)
                .withInt("type", SmsAccountActivity.LOGIN)
                .navigation());*/
       /* tvForgotPsd.setOnClickListener(view ->
                ARouter.getInstance().build(ARouterUrlKt.AccountEditBySmsUrl).withInt("type", 2).navigation());*/

      /*  ivWechatLogin.setOnClickListener(view -> {
            loginType = 1;
            final IWXAPI api;
            api = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID, false);
            //将应用的appid注册到微信
            api.registerApp(Constant.WX_APP_ID);
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_kaiwulink";
            api.sendReq(req);
        });*/
       /* ivAliLogin.setOnClickListener(view -> {
            loginType = 2;
            //mPresenter.requestAlipayAuth();
        });*/

        initEditEvent();

        SecVerify.preVerify(new OperationCallback<Void>() {
            @Override
            public void onComplete(Void data) {
                LogUtils.d("秒验预登陆成功");
            }

            @Override
            public void onFailure(VerifyException e) {
                LogUtils.e("秒验预登陆失败:" + e.getCode() + ":" + e.getMessage());
            }
        });

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent loginEvent) {
        WechatLoginRequest wechatLoginRequest =
                new WechatLoginRequest(null, null, loginEvent.getOpenId());
        mOpenId = loginEvent.getOpenId();
        mPresenter.loginByWechat(mOpenId, null, null);
        // mPresenter.wechatLogin(wechatLoginRequest);
    }

    @Override
    public void loginSuccess() {
        /*ARouter.getInstance()
                .build(ARouterUrlKt.MainRouterUrl)
                .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK)
                .withBoolean("EXTRA_KEY_REFRESH", true)
                .navigation(this);
        finish();*/
        //showMessage("login success");
        if (getApp().getUserInfo().getLastCommunityId() == null || getApp().getUserInfo().getLastCommunityId() < 0) {
            ARouter.getInstance().build(ARouterUrlKt.CommunityUpdateUrl).navigation();
        } else {
            ARouter.getInstance().build(ARouterUrlKt.MainRouterUrl).navigation();

        }
    }

    @Override
    public void wechatBindMobild(String openId) {
        hideLoading();
        ARouter.getInstance().build(ARouterUrlKt.ForgetPassUrl)
                .withInt("way", 1)
                .withString("extra", openId)
                .navigation();
    }

    public void sendVerifyCodeComplete() {
        showMessage("验证码已发送");
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    /*   @Override
       public void thirdLoginSuccess(int code) {
           if (code == 90) {
               ARouter.getInstance().build(ARouterUrlKt.AccountEditBySmsUrl)
                       .withInt("type", SmsAccountActivity.BIND)
                       .withInt("loginType", loginType)
                       .withString("openId", mOpenId)
                       .withString("authCode", authCode).navigation();
           } else {
               ARouter.getInstance().build(ARouterUrlKt.MainRouterUrl).navigation();
               finish();
           }
       }

       @Override
       public void getAlipayAuth(@NotNull String auth) {
           infoStr = auth;
           getAuthResultFromAuthInfo(infoStr);
       }
   */
    private void getAuthResultFromAuthInfo(String alipay_sdk_auth_info) {
        Disposable disposable = Observable.create((ObservableOnSubscribe<AuthResult>) emitter -> {
            // 构造AuthTask 对象
            AuthTask authTask = new AuthTask(PsdLoginActivity.this);
            // 调用授权接口，获取授权结果
            Map<String, String> result = authTask.authV2(alipay_sdk_auth_info, true);
            AuthResult authResult = new AuthResult(result, true);
            emitter.onNext(authResult);
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::handleAlipayRlt);

        subscribe(disposable);

    }

    /**
     * 解析支付宝callback
     *
     * @param authResult AuthResult
     */
    private void handleAlipayRlt(AuthResult authResult) {
        String resultStatus = authResult.getResultStatus();
        // 判断resultStatus 为“9000”且result_code为“200”则代表授权成功，
        if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
            // 获取alipay_open_id，调支付时作为参数extern_token 的value传入，则支付账户为该授权账户，这个支付先不做

            AlipayLoginRequest alipayLoginRequest =
                    new AlipayLoginRequest(authResult.getAuthCode(), null, null);
            authCode = authResult.getAuthCode();
            // mPresenter.alipayLogin(alipayLoginRequest);//开发者自己的方法
        } else {
            if (TextUtils.isEmpty(authResult.getAuthCode())) {
                showMessage("授权取消");
            } else
                showMessage("授权失败");
        }

    }

    /**
     * 添加输入框监听
     */
    private void initEditEvent() {
        etPhoneNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                boolean hasText = (s.toString().trim().length() > 0);
                ivPhoneClear.setVisibility(hasText ? View.VISIBLE : View.GONE);

                boolean hasPwd = (etPassword.getText().toString().trim().length() > 0);

                tvLogin.setEnabled(hasText && hasPwd);

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                boolean hasPwd = (s.toString().trim().length() > 0);
                boolean hasUname = (etPhoneNumber.getText().toString().trim().length() > 0);
                tvLogin.setEnabled(hasUname && hasPwd);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void loginWechat() {
        loginType = 1;
        final IWXAPI api;
        api = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID, false);
        //将应用的appid注册到微信
        api.registerApp(Constant.WX_APP_ID);
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_kaiwulink";
        if (!api.isWXAppInstalled()) {
            showMessage(getString(R.string.please_install_wechat));
            return;
        }
        api.sendReq(req);
    }


    private void loginFast() {
        fastLoginInit();
        SecVerify.verify(new VerifyCallback() {
            @Override
            public void onOtherLogin() {
                LogUtils.d("onOtherLogin");
            }

            @Override
            public void onUserCanceled() {
                LogUtils.d("onUserCanceled");
            }

            @Override
            public void onComplete(VerifyResult verifyResult) {
                mPresenter.loginByFast(verifyResult.getToken(), verifyResult.getOpToken(), verifyResult.getOperator());
            }

            @Override
            public void onFailure(VerifyException e) {
                LogUtils.e("onFailure");
            }
        });
    }

    private void fastLoginInit() {
        UiSettings uiSettings = new UiSettings.Builder()
                .setNumberOffsetY(150)
                .setLoginBtnImgId(R.drawable.shape_login_default_btn)
                .setLoginBtnOffsetY(210)
                .setSwitchAccText("其他手机号码登录")
                .setSwitchAccTextSize(R.dimen.dp_15)
                .setSwitchAccHidden(true)
                //.setSwitchAccColorId(R.color.app_color_dark)
                .setSwitchAccOffsetY(280)
                .setAgreementColorId(-0x14a4a7)
                .setLogoImgId(R.mipmap.ic_fastlogin_logo)
                .setLogoHeight(43)
                .setLogoWidth(43)
                .setLogoOffsetY(100)
                .setCusAgreementNameId1("《用户协议》")
                .setCusAgreementUrl1(Constant.LOGIN_TIP_WEB_URL)
                .setAgreementTextAnd1("、")
                .setAgreementTextStart("登录/注册即表示同意")
                .setAgreementCmccText("《中国移动隐私协议》")
                .setAgreementCuccText("《中国联通隐私协议》")
                .setAgreementCtccText("《中国电信隐私协议》")
                .setAgreementTextEnd("并授权家院里获取本机号码")
                .setAgreementOffsetY(320)
                .build();

        List<View> viewList = new ArrayList<>();

        RelativeLayout containerTitle = new RelativeLayout(this);
        TextView textView = new TextView(this);
        textView.setText("您好");
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
        textView.setTextColor(ContextCompat.getColor(this, R.color.black_color));
        RelativeLayout.LayoutParams titleParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        titleParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        titleParams.setMargins(0, SizeUtils.dp2px(24), 0, 0);
        // containerTitle.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
        containerTitle.setLayoutParams(titleParams);
        containerTitle.setGravity(Gravity.CENTER);
        containerTitle.addView(textView);

        viewList.add(containerTitle);

        View btnOtherPhone = View.inflate(this, R.layout.widget_fastlogin_other_btn, null);
        RelativeLayout.LayoutParams btnOtherPhoneParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                SizeUtils.dp2px(44f));
        btnOtherPhoneParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        btnOtherPhoneParams.setMargins(SizeUtils.dp2px(36f), SizeUtils.dp2px(260f), SizeUtils.dp2px(36f), 0);
        btnOtherPhone.setLayoutParams(btnOtherPhoneParams);

        btnOtherPhone.findViewById(R.id.btn_pass).setOnClickListener(v -> {
            SecVerify.finishOAuthPage();
            //  ARouter.getInstance().build(LoginRouterUrl).navigation()
        });

        View layoutFlag = View.inflate(this, R.layout.widget_fastlogin_other_flag, null);
        RelativeLayout.LayoutParams flagParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);

        flagParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        flagParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        flagParams.setMargins(0, 0, 0, SizeUtils.dp2px(128f));
        layoutFlag.setLayoutParams(flagParams);

        View layoutOther = View.inflate(this, R.layout.widget_fastlogin_other, null);
        layoutOther.findViewById(R.id.iv_wechat).setOnClickListener(v -> loginWechat());
        //layoutOther.findViewById(R.id.iv_qq).setOnClickListener(v -> showMessage("QQ登录"));
        RelativeLayout.LayoutParams otherParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        otherParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        otherParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        otherParams.setMargins(0, 0, 0, SizeUtils.dp2px(80f));
        layoutOther.setLayoutParams(otherParams);

        viewList.add(btnOtherPhone);
        //viewList.add(layoutFlag);
        // viewList.add(layoutOther);
        CustomUIRegister.addCustomizedUi(viewList, null);
        SecVerify.setUiSettings(uiSettings);
    }


}
